using System;
using System.Linq;
using System.Threading.Tasks;
using GiteeApi.Dtos;
using GiteeApi.Models;
using GiteeApi.Utils;
using Microsoft.EntityFrameworkCore;

namespace GiteeApi.Services
{
    public class GiteeAPIServices
    {
        private readonly giteeapiContext _giteeapiContext;

        public GiteeAPIServices(giteeapiContext giteeapiContext)
        {
            _giteeapiContext = giteeapiContext;
        }
        
        /// <summary>
        /// 获取私钥
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns>私钥</returns>
        public async Task<RequestBack> GetAccessToken(int userid, string password = "")
        {
            // POST 请求认证
            if (password != "")
            {
                if (await _giteeapiContext.UserInfos.CountAsync(a => a.Id == userid && a.Password == MD5Util.Get(password)) == 0)
                {
                    return new(0, "密码错误");
                }
            }
            
            // 获取私钥
            var accessToken = await _giteeapiContext.AccessTokens.FirstOrDefaultAsync(x => x.UserId == userid && x.Delete == 0);
            if (accessToken is null)
            {
                return new(0, "此账号未设置私钥！");
            }

            return new(1, "获取成功", accessToken.AccessToken1);
        }
    }
}